<?php
namespace api\user\controller;

use think\Db;
use think\Validate;
use fast\Http;
use api\common\controller\RestBaseController;

class PayController extends RestBaseController
{
    /**
     * 支付
     * @author M
     * @data             2020-02-11
     * @param  [type] $order_id  [description]
     * @return [type]            [description]
     */
    public function index()
    {
        $param    = $this->request->param();
        $validate = new Validate([
            'order_id'     =>'require|number|gt:0',
            'pay_type'     =>'require',
        ]);
        $validate->message([
            'order_id.require'     =>'订单参数有误',
            'order_id.number'      =>'订单参数有误',
            'order_id.gt'          =>'订单参数有误',
            'pay_type.require'     =>'请选择支付方式',
        ]);
        if (!$validate->check($param)) {
            $this->error($validate->getError());
        }
        $thirdpay_config = config('thirdpay_config');
        $order_id = $param['order_id'];
        $pay_type = $param['pay_type'] ==1?'923':'922';//922:PDD支付宝支付,923:PDD微信支付
        $order = Db::name('user_order')
        ->where(['id'=>$order_id,'order_status'=>4,'order_type'=>2])
        ->find();
        if(!$order){
        	$this->error("订单不存在");
        }
        $params = array(
            'pay_memberid'    =>$thirdpay_config['pay_memberid'],
            'pay_orderid'     =>$order['order_no'],
            'pay_applydate'   =>date('Y-m-d H:i:s'),
            'pay_bankcode'    =>$pay_type,
            'pay_notifyurl'   =>url('user/pay/notifyurl',[],'',true),
            'pay_callbackurl' =>url('user/pay/returnurl',[],'',true),
            'pay_amount'      => intval($order['sell_price'])
        );
        ksort($params);
        $md5str = "";
        foreach ($params as $key => $val) {
            $md5str = $md5str . $key . "=" . $val . "&";
        }
        $sign = strtoupper(md5($md5str . "key=" . $thirdpay_config['key']));
        $params["pay_md5sign"] = $sign;
        $params['pay_productname'] ='OTC买入';

        $http = new \fast\Http();
        $res = $http->post($thirdpay_config['payurl'], $params);
        file_put_contents('./res.txt', $res);
        $res = json_decode($res);

        if($res['status'] =='error'){
            $msg = isset($res['msg'])?$res['msg']:'支付失败';
            $this->error($msg);
        }else{
           $this->success('支付成功'); 
        }
    }

    public function notifyurl(){
		$param = $this->request->param();
	    $returnArray = array( // 返回字段
            "memberid"       =>  $param["memberid"], // 商户ID
            "orderid"        =>  $param["orderid"], // 订单号
            "amount"         =>  $param["amount"], // 交易金额
            "datetime"       =>  $param["datetime"], // 交易时间
            "transaction_id" =>  $param["transaction_id"], // 支付流水号
            "returncode"     =>  $param["returncode"],
        );
        $thirdpay_config = config('thirdpay_config');
        $md5key = $thirdpay_config['key'];
        ksort($returnArray);
        reset($returnArray);
        $md5str = "";
        foreach ($returnArray as $key => $val) {
            $md5str = $md5str . $key . "=" . $val . "&";
        }
        $sign = strtoupper(md5($md5str . "key=" . $md5key));
        if ($sign == $param["sign"]) {
            if ($param["returncode"] == "00") {
                   $str = "交易成功！订单号：".$param["orderid"];
                   file_put_contents("success.txt",$str."\n", FILE_APPEND);
                   exit("ok");
            }
        }
    }


}
